package agend.client.behaviours;

import jade.content.lang.Codec.CodecException;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.ContainerID;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.FIPANames;
import jade.domain.JADEAgentManagement.CreateAgent;
import jade.domain.JADEAgentManagement.JADEManagementOntology;
import jade.lang.acl.ACLMessage;
import agend.client.utils.GetAID;

/**
 * Behaviour che invia una richiesta all'AMS sul server
 * per avviare un agente se quest'ultimo non esiste ed inoltre passa all' agente le sue credenziali google
 */
public class RequestStartAgentBehaviour extends OneShotBehaviour {

	private static final long serialVersionUID = 1L;
	
	private String username;
	private String password;

	@Override
	public void action() {

		AID amsServerAid = GetAID.ams();
		
		ContainerID containerID = new ContainerID();
		containerID.setMain(true);
		containerID.setName("Main-Container");		
		
		CreateAgent createAgent = new CreateAgent();
		createAgent.setAgentName(username.replace("@", "#"));  					//Sostituisco @ con # nel nome dell' agente 
		createAgent.setClassName("agend.agents.AgendAgent");
		
		String [] credenziali = new String [] {username,password}; 				//Mentre le credenziali per l' accesso a google rimangono le stesse
		createAgent.addArguments(credenziali);
		createAgent.setContainer(containerID);

		Action action = new Action();
		action.setActor(amsServerAid);
		action.setAction(createAgent);

		ACLMessage amsRequest = new ACLMessage(ACLMessage.REQUEST);
		amsRequest.setSender(myAgent.getAID());
		amsRequest.addReceiver(amsServerAid);
		amsRequest.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
		amsRequest.setOntology(JADEManagementOntology.NAME);
		amsRequest.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);

		try {
			
			myAgent.getContentManager().registerLanguage(SLCodec.class.newInstance(), "fipa-sl0");
			myAgent.getContentManager().registerOntology(JADEManagementOntology.getInstance());
			myAgent.getContentManager().fillContent(amsRequest, action);
			
			myAgent.send(amsRequest);			
			
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CodecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OntologyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	

}
